package com.example.ndktest;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.os.Environment;
import android.util.Log;

public class FileLoger implements Runnable {
	private final Object mutex = new Object();
	private volatile boolean isRecording;
	private File logFile;
	DataOutputStream dataOutputStreamInstance;
	private List<String> list;
	private static final String LOG_BUSHCAT = "Log_bushcat";

	public FileLoger() {
		super();
		logFile = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/android_log.txt");

		list = Collections.synchronizedList(new LinkedList<String>());
	}

	public void init() {
		BufferedOutputStream bufferedStreamInstance = null;
		boolean result;
		if (logFile.exists()) {
			logFile.delete();
		}

		try {
			result = logFile.createNewFile();
		} catch (IOException e) {
			throw new IllegalStateException("Cannot create file: "
					+ logFile.toString());
		}

		try {
			bufferedStreamInstance = new BufferedOutputStream(
					new FileOutputStream(logFile));
		} catch (FileNotFoundException e) {
			throw new IllegalStateException("Cannot Open File", e);
		}

		dataOutputStreamInstance = new DataOutputStream(bufferedStreamInstance);
	}

	public void run() {
		while (this.isRecording()) {

			if (list.size() > 0) {
				String tempStr = list.remove(0);
				try {
						dataOutputStreamInstance.writeChars(tempStr+"\r\n");
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
		stop();
	}

	public void putData(String str) {
		list.add(str);
	}

	public void stop() {
		try {
			dataOutputStreamInstance.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setRecording(boolean isRecording) {
		synchronized (mutex) {
			this.isRecording = isRecording;
			if (this.isRecording) {
				mutex.notify();
			}
		}
	}

	public boolean isRecording() {
		synchronized (mutex) {
			return isRecording;
		}
	}
}
